package org.example;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Hello world!
 *
 */
@Slf4j(topic = "")
public class 两阶段终止模式
{
    public static void main( String[] args ) throws ExecutionException, InterruptedException {
        TwoPhaseTermination twoPhaseTermination = new 两阶段终止模式().new TwoPhaseTermination();
        twoPhaseTermination.start();

        Thread.sleep(3000);
        twoPhaseTermination.interrupt();
    }

    class TwoPhaseTermination {
        private Thread monitor;

        public void start() {
            monitor = new Thread(() -> {
                while (true) {
                    Thread thread = Thread.currentThread();
                    if (thread.isInterrupted()) {
                        log.debug("被打断了");
                        break;
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                        log.debug("正在执行");
                    } catch (InterruptedException e) {
                        log.debug("休眠打断");
                        e.printStackTrace();
                        System.out.println(Thread.interrupted());


                    }
                }
            });
            monitor.start();
        }

        public void interrupt() {
            monitor.interrupt();
        }
    }
}
